#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/wait.h>
//from page 554
void my_waitpid(){
	pid_t pid;
	pid=fork();
	if(pid <0){
		perror("fork fail");
		exit(1);
	}
	if(pid==0){
		int i;
		for(i=3;i>0;i--){
			printf("the child process\n");
			sleep(1);
		}
		exit(3);
	}else{
		int stat_val;
		waitpid(pid,&stat_val,0);
		if(WIFEXITED(stat_val))
			printf("child exited with code %d\n",WEXITSTATUS(stat_val));
		else if(WIFSIGNALED(stat_val))
			printf("child terminated abnorymally,signal %d\n",WTERMSIG(stat_val));
	}
}

void basic_fork()
{
	pid_t pid;
	char *message=NULL;
	int n;
	pid=fork();
	if(pid<0)
	{
		printf("fork child fail\n");
		exit(1);
	}
	if(pid==0){
		message="this is a child\n";
		n=6;
	}else{
		message="this is a parent\n";
		n=3;
	}
	for(;n>0;n--){
		printf(message);
		sleep(3);
	}
}

void my_pipe()//page 572
{
	int n;
	int fd[2];
	pid_t pid;
	char line[80];
	if(pipe(fd)<0){
		printf("pipe faili\n");
		exit(1);
	}
	if((pid=fork())<0){
		printf("fork fail\n");
		exit(1);
	}
	if(pid >0 )//parent
	{
		close(fd[0]);
		printf("parent write\n");
		write(fd[1],"hello world\n",12);
		wait(NULL);
	}else{ //child
		close(fd[1]);
		printf("child read\n");
		n=read(fd[0],line,80);
		write(STDOUT_FILENO,line,n);
	}
}

int main(int argc, char **argv)
{
	basic_fork();
	my_waitpid();
	my_pipe();
	return 0;
}
